﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Cartoon.Model;
using Cartoon.Logic;
using System.Threading;
using System.Windows.Threading;
using Cartoon.Skin;

namespace CartoonViewer
{
    public enum ChapterState
    { 
        UnDownload=0,Downloading,Downloaded
    }

    public delegate void DownloadChapterDelegate(object sender,Chapter chp);

    /// <summary>
    /// UC_Chapter.xaml 的交互逻辑
    /// </summary>
    public partial class UC_Chapter : UserControl
    {
        public UC_Chapter()
        {
            InitializeComponent();
        }

        public UC_Chapter(Chapter _chp)
            : this()
        {
            this.chp = _chp;
            InitView();
        }

        public UC_Chapter(ICartoonView _container, Chapter _chp)
            : this()
        {
            this._Container = _container;
            this.chp = _chp;
            InitView();
        }

        #region 属性

        public event DownloadChapterDelegate Download;

        protected Chapter chp;
        protected ICartoonView _Container;
        public ICartoonView Container { get { return this._Container; } }
        DispatcherTimer dTimer = new DispatcherTimer(DispatcherPriority.ApplicationIdle);
        #endregion

        public Chapter GetChapter()
        {
            return this.chp;
        }

        protected void InitView()
        {
            this.Lb_ChapterTitle.Content = this.chp.Id + "话";
            this.SetState(ChapterState.UnDownload);

            this.CheckState();
        }

        public void CheckState()
        {
            dTimer.Tick += new EventHandler((obj, av) =>
            {
                if (this.IsDownloaded() == true)
                {
                    this.SetState(ChapterState.Downloaded);
                }
                else
                {
                    this.SetState(ChapterState.UnDownload);
                }

                dTimer.Stop();
            });
            dTimer.Interval = new TimeSpan(2000);
            dTimer.Start(); 
        }

        protected bool IsDownloaded()
        {
            string chppath = new System.IO.DirectoryInfo( System.IO.Path.Combine( this._Container.CartoonSavePath , this.chp.comic.Name , this.chp.Id.ToString() )).FullName;

            string chpcfgpath = System.IO.Path.Combine(chppath ,"Chapter.xml");

            Chapter c = this.chp.Load(chpcfgpath);

            if (c != null)
            {
                this.chp.PicListUrl = c.PicListUrl;
                this.chp.PicListUrlString = c.PicListUrlString;
                this.chp.PicCount = c.PicCount;
                this.chp.PicAllSize = c.PicAllSize;
            }

            if (this.chp.PicListUrl == null) return false;

            foreach (string picurl in this.chp.PicListUrl)
            {
                string picpath = System.IO.Path.Combine(chppath , System.IO.Path.GetFileName(picurl));
                if (!System.IO.File.Exists(picpath))
                {
                    return false;
                }
            }

            return true;
        }

        protected ChapterState State;

        public double W
        {
            get
            {
                return this.Gd_Chapter.Width;
            }
        }

        public double H
        {
            get
            {
                return this.Gd_Chapter.Height;
            }
        }

        protected void MouseEnterState(System.Windows.Controls.Control e)
        {
            e.Foreground = Brushes.Blue;
            e.Cursor = Cursors.Hand;
        }

        protected void MouseLeaveState(System.Windows.Controls.Control e)
        {
            e.Foreground = Brushes.Black;
            e.Cursor = Cursors.None;
        }

        private void Lb_Download_MouseEnter(object sender, MouseEventArgs e)
        {
            this.MouseEnterState(this.Lb_Download);
            
        }

        private void Lb_Download_MouseLeave(object sender, MouseEventArgs e)
        {
            this.MouseLeaveState(this.Lb_Download);
             
        }

        private void Lb_Download_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.OnDownLoad(this.chp);
        }

        protected void OnDownLoad(Chapter chp)
        {
            if (this.Download != null)
            {
                this.Download(this,chp);
            }
        }

        protected void HideControl(FrameworkElement c)
        {
            this.SetControlVisibility(c, Visibility.Collapsed);
        }

        protected void ShowControl(FrameworkElement c)
        {
            this.SetControlVisibility(c, Visibility.Visible);
        }

        protected void SetControlVisibility(FrameworkElement c, Visibility v)
        {
            c.Dispatcher.Invoke(new Action(() =>
            {
                c.Visibility = v;
            }));
        }

        protected void SetState(ChapterState cs)
        { 
            this.State = cs;

            this.HideControl(this.PlUnDownload);
            this.HideControl(this.PlDownloading);
            this.HideControl(this.PlDownloaded);
            //this.Gd_Chapter.Dispatcher.Invoke(new Action(() =>
            //{
            //    this.Gd_Chapter.Background = null;
            //}));
            switch (cs)
            { 
                case ChapterState.UnDownload:
                    this.ShowControl(this.PlUnDownload);
                    break;
                case ChapterState.Downloading:
                    this.ShowControl(this.PlDownloading);
                    break;
                case ChapterState.Downloaded:
                    this.ShowControl(this.PlDownloaded);

                    this.Gd_Chapter.Dispatcher.Invoke(new Action(() =>
                    {
                        this.Gd_Chapter.Background = Brushes.AliceBlue;
                    }));

                    break;
                default: break;
            }
        } 

        protected Belyn.Common.Web.IDownload downloader;
        public Belyn.Common.Web.IDownload Downloader
        {
            get { return this.downloader; }
            set
            {
                this.dTimer.Stop();

                this.downloader = value;

                this.downloader.Canceled += new Belyn.Common.Web.DownloadDelegate(downloader_Canceled);
                this.downloader.Downloading += new Belyn.Common.Web.DownloadDelegate(downloader_Downloading);
                this.downloader.SpeedChanged += new Belyn.Common.Web.DownloadDelegate(downloader_SpeedChanged);
                this.downloader.Started += new Belyn.Common.Web.DownloadDelegate(downloader_Started);
                this.downloader.Stoped += new Belyn.Common.Web.DownloadDelegate(downloader_Stoped);
                this.downloader.Suspended += new Belyn.Common.Web.DownloadDelegate(downloader_Suspended);
                this.downloader.Failed += new Belyn.Common.Web.DownloadFailedDelegate(downloader_Failed);

                if (this.downloader.State == Belyn.Common.Web.DownloadState.Downloading
                    || this.downloader.State == Belyn.Common.Web.DownloadState.Suspend)
                {
                    this.SetState(ChapterState.Downloading);
                }
                else if (this.downloader.State == Belyn.Common.Web.DownloadState.Success)
                {
                    this.SetState(ChapterState.Downloaded);
                }
                else
                {
                    this.SetState(ChapterState.UnDownload);
                }

                CartoonDownload cd = this.downloader as CartoonDownload;
                if (cd != null)
                {
                    this.chp = cd.DownloadChapter;
                }

                this.SetProgress(this.downloader);

            }
        }

        private void downloader_Failed(Belyn.Common.Web.IDownload d, string message)
        {
            this.SetState(ChapterState.UnDownload);
        }

        protected void SetProgressValue(ProgressBar p, double value)
        {
            p.Dispatcher.Invoke(new Action(() =>
            {
                p.Value = value;
            }));
        }

        protected void SetTextBlockValue(TextBlock t, string value)
        {
            t.Dispatcher.Invoke(new Action(() =>
            {
                t.Text= value;
            }));
        }

        private void downloader_Suspended(Belyn.Common.Web.IDownload d)
        {
             
        }

        private void downloader_Stoped(Belyn.Common.Web.IDownload d)
        {
            this.SetState(ChapterState.UnDownload);
        }

        private void downloader_Started(Belyn.Common.Web.IDownload d)
        {
            this.SetState(ChapterState.Downloading);
        }

        private void downloader_SpeedChanged(Belyn.Common.Web.IDownload d)
        {
            if (this.State != ChapterState.Downloading)
            {
                this.SetState(ChapterState.Downloading);
            }

            this.SetProgress(d);

            if (d.Over == true)
            {//下载完成 
                this.SetState(ChapterState.Downloaded);

            }
        }

        private void downloader_Downloading(Belyn.Common.Web.IDownload d)
        {

            if (d.Over == true)
            {//下载完成 
                this.SetState(ChapterState.Downloaded);

            }
        }

        private void SetProgress(Belyn.Common.Web.IDownload d)
        {

            this.SetProgressValue(this.PbDownloading, d.Progress);
            this.SetTextBlockValue(this.LbDownloadingProgress, (d.Progress>0 ? (d.Progress * 100).ToString("#.##"):"0") + "%");
        }

        private void downloader_Canceled(Belyn.Common.Web.IDownload d)
        {
            this.SetState(ChapterState.UnDownload);
        }  

        private void LbLook_MouseEnter(object sender, MouseEventArgs e)
        {
            this.MouseEnterState(this.LbLook);
        }

        private void LbLook_MouseLeave(object sender, MouseEventArgs e)
        {
            this.MouseLeaveState(this.LbLook);
        }

        //浏览漫画
        private void LbLook_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ISkinService SkinS = this.Container.Skin;
            W_ChapterPictureViewer picViewer = new W_ChapterPictureViewer(this.Container, SkinS, this.chp);
            
            picViewer.Show();
         
        }

    }
}
